﻿
using System;
// Includeing the M2Mqtt Library
using M2MqttClient = uPLibrary.Networking.M2Mqtt.MqttClient;
using uPLibrary.Networking.M2Mqtt.Messages;

namespace BtcsCon
{
    class MqttSubscriber
    {
        private string broker_ip_;
        public int broker_port_ = 1833; // Default port is 1833
        private M2MqttClient client_;
        private string client_id_;
        private string[] sub_topics_;
        public MqttSubscriber(string[] sub_topics, string broker_ip, string client_id, string username = "",
             string passwd = "", M2MqttClient.MqttMsgPublishEventHandler msg_handler = null)
        {
            broker_ip_ = broker_ip;
            client_id_ = client_id;
            sub_topics_ = sub_topics;
            msg_handler = msg_handler == null ? defaultMsgHandler : msg_handler;
            // Connect to Broker
            client_ = new M2MqttClient(broker_ip_);
            client_.MqttMsgPublishReceived += msg_handler;
            client_.Connect(client_id_, username, passwd);
            client_.Subscribe(sub_topics_, setQosLevel(sub_topics_));
        }

        private void defaultMsgHandler(object sender, MqttMsgPublishEventArgs e)
        {
            System.Console.WriteLine("Recv(abandoned) > {0}", e.Message);
        }

        // Subscribe to the topic with QoS 2
        private byte[] setQosLevel(string[] sub_topics_)
        {
            int len = sub_topics_.Length;
            byte[] qos_levels = new byte[len];
            for (int i = 0; i < len; i++)
            {
                qos_levels[i] = MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE;
            }
            return qos_levels;
        }
    }
}
